<?php

/**
 * 验证参数合法性
 *
 * @param array $params 验证的参数
 * @access public
 * @return boolean
 */
function validateParams(&$params) {
    if(!is_dir($params[1])) {
        printf("无效目录!\n");
        return false;
    }
    if(!is_writeable($params[1])) {
        printf("目录不可写，请确认！\n");
        return false;
    }
    if(!$params[2]) {
        printf("缺少替换规则！\n");
        return false;
    }
    if(!isset($params[3])) {
        printf("缺少替换内容！");
        return false;
    }

    return true;
}

/**
 * 更改目录里的文件名
 *
 * @param array $params
 * @access public
 * @return boolean 
 */
function changeDirFileName($params) {
    if(false === validateParams($params)) {
        helpInfo();
        return false;
    }
    $dirPath    = $params[1];
    $reMode     = $params[2];
    $reString   = $params[3];
    $filterMode = empty($params[4]) ? '/^\./' : $params[4];
    $dirHandle  = opendir($dirPath);
    $totalFailFile      = 0;
    $totalSuccessFile   = 0;
    while(true == ($file = readdir($dirHandle))) {
        if(preg_match($filterMode, $file)) {
            continue;
        }
        $newFileName    = preg_replace($reMode, $reString, $file);
        if(rename($dirPath . '/' . $file, $dirPath . '/' . $newFileName)) {
            printf("转换 %s -> %s [Success]\n", $file, $newFileName);
            $totalSuccessFile ++;
        } else {
            printf("转换 %s -> %s [Fail!]\n", $file, $newFileName);
            $totalFailFile ++;
        }
    }

    printf("一共 %d 个文件参与换名。Success: %d 个；Fail: %d个。\n", ($totalSuccessFile + $totalFailFile) , $totalSuccessFile, $totalFailFile);
}

/**
 * 显示帮助信息
 *
 * @param null
 * @access public
 * @return void
 */
function helpInfo() {
    printf("[!]请输入目标目录地址^_^。\n");
    printf("使用说明：\n");
    printf("1. >php ChangeDirFileName.php 目标目录 替换规则 替换内容 过滤规则；\n");
    printf("2. 替换规则必须，替换内容必须！\n");
    printf("3. 过滤规则，默认为/^\./;\n");
    printf("PS: 反斜杆得用两个才有效。如，\ -> \\\\;\n");
    printf("Version: 1.0\n");
    printf("Author: 九九\n");
    printf("Date: 2011.09.14\n");
}


//开始做事...
if($argc > 1) {
    changeDirFileName($argv);
} else {
    helpInfo();
}

?>
